package controllers

import (
	"bytes"
	"devOpsApi/base"
	"devOpsApi/common/util"
	"devOpsApi/libs"
	"devOpsApi/middleware"
	"devOpsApi/model"
	"fmt"
	"github.com/kataras/iris"
	"strconv"
	"strings"
)

type UserController struct {
	base.BController
}

//用户列表
func (c *UserController) GetList() {
	UserModel := model.NewUser()
	page, err := strconv.Atoi(c.Ctx.URLParam("page"))
	if err != nil || page < 1 {
		page = 1
	}
	pageSize, err := strconv.Atoi(c.Ctx.URLParam("pageSize"))
	if err != nil || pageSize < 1 {
		pageSize = 20
	}
	list, total, pages := UserModel.List(uint(page), uint(pageSize))
	c.OutDataJson(iris.Map{"list": list, "total": total, "pages": pages, "currentPage": page}, iris.StatusOK, "success")
}

//用户列表
func (c *UserController) GetPublicList() {
	UserModel := model.NewUser()
	c.OutDataJson(UserModel.GetAllUser(), iris.StatusOK, "success")
}

//用户信息
func (c *UserController) GetPublicUserInfo() {
	user_model := model.NewUser()
	userInfo, _ := user_model.GetUserByUserId(middleware.GetTokenUserId(c.Ctx))
	UserModel := model.NewUser()
	UserRoleRouteModel := model.NewUserRoleRoute()
	RoleId, RoleName := UserModel.GetUser2Role(uint(userInfo.ID))
	RoleNodes, _ := UserRoleRouteModel.GetAllRoutes(RoleId)
	NewRoleNodes := []string{}
	for _, v := range RoleNodes {
		if v[:4] == "GET/" {
			old := strings.Replace(v, "GET/", "", -1)
			NewRoleNodes = append(NewRoleNodes, old[2:])
		}
	}
	userInfo.RoleId = RoleId
	userInfo.RoleName = RoleName
	userInfo.RoleNodes = strings.Join(NewRoleNodes, ",")
	c.OutDataJson(userInfo, iris.StatusOK, "success")
}

//修改密码
func (c *UserController) PostUpdatePwd() {
	userId := c.Ctx.PostValueIntDefault("uid", 0)
	password := c.Ctx.PostValueDefault("password", "")
	if userId == 0 || password == "" {
		c.OutDataJson("", iris.StatusBadRequest, "参数丢失")
		return
	}
	UserModel := model.NewUser()
	if err := UserModel.UpdatePwd(uint(userId), password); err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}
	c.OutDataJson("", iris.StatusOK, "success")
}

//修改个人密码
func (c *UserController) PostUpdateSelfPwd() {
	userId := middleware.GetTokenUId(c.Ctx)
	password := c.Ctx.PostValueDefault("password", "")
	if userId == 0 || password == "" {
		c.OutDataJson("", iris.StatusBadRequest, "参数丢失")
		return
	}
	UserModel := model.NewUser()
	if err := UserModel.UpdatePwd(uint(userId), password); err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}
	c.OutDataJson("", iris.StatusOK, "success")
}

//更新用户角色
func (c *UserController) PostRoleUserUpdate() {
	userId := c.Ctx.PostValueIntDefault("uid", 0)
	roleId := c.Ctx.PostValueIntDefault("roleId", 0)
	if userId == 0 || roleId == 0 {
		c.OutDataJson("", iris.StatusBadRequest, "参数丢失")
		return
	}
	if userId == 1 {
		c.OutDataJson("", iris.StatusBadRequest, "内置管理员不允许修改!")
		return
	}

	UserRoleUserModel := model.NewUserRoleUser()
	if err := UserRoleUserModel.UpdateRole(uint(userId), uint(roleId)); err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}
	c.OutDataJson("", iris.StatusOK, "success")
}

//更新用户状态
func (c *UserController) PostStatusUpdate() {
	userId := c.Ctx.PostValueIntDefault("uid", 0)
	status := c.Ctx.PostValueIntDefault("status", 0)
	if userId == 0 {
		c.OutDataJson("", iris.StatusBadRequest, "参数丢失")
		return
	}
	if userId == 1 {
		c.OutDataJson("", iris.StatusBadRequest, "内置管理员不允许修改!")
		return
	}
	UserRoleUserModel := model.NewUserRoleUser()
	if err := UserRoleUserModel.UpdateStatus(uint(userId), int(status)); err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}
	c.OutDataJson("", iris.StatusOK, "success")
}

//用户删除
func (c *UserController) PostDelete() {
	userModel := model.NewUser()
	uid := c.Ctx.PostValueIntDefault("uid", 0)
	if uid == 0 {
		c.OutDataJson("", iris.StatusBadRequest, "参数错误")
		return
	}
	if uid == 1 {
		c.OutDataJson("", iris.StatusBadRequest, "不允许删除的账号")
		return
	}
	err := userModel.Delete(uint(uid))
	if err == nil {
		c.OutDataJson("", iris.StatusOK, "success")
	} else {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
	}
}

//角色列表
func (c *UserController) GetPublicRole() {
	roleModel := model.NewUserRole()
	_, Role := roleModel.GetAllRole()
	c.OutDataJson(Role, iris.StatusOK, "success")
}

//角色列表
func (c *UserController) GetRole() {
	roleModel := model.NewUserRole()
	_, Role := roleModel.GetAllRole()
	c.OutDataJson(Role, iris.StatusOK, "success")
}

//角色新增
func (c *UserController) PostRoleCreate() {
	roleModel := model.NewUserRole()
	_ = c.Ctx.ReadForm(roleModel)
	err := roleModel.RoleCreate()
	if err == nil {
		c.OutDataJson("", iris.StatusOK, "success")
	} else {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
	}
}

//角色新增
func (c *UserController) PostRoleUpdate() {
	roleModel := model.NewUserRole()
	_ = c.Ctx.ReadForm(roleModel)
	err := roleModel.RoleUpdate()
	if err == nil {
		c.OutDataJson("", iris.StatusOK, "success")
	} else {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
	}
}

//角色删除
func (c *UserController) PostRoleDelete() {
	roleModel := model.NewUserRole()
	id := c.Ctx.PostValueIntDefault("id", 0)
	if id == 0 {
		c.OutDataJson("", iris.StatusBadRequest, "参数错误")
		return
	}
	if id == 1 {
		c.OutDataJson("", iris.StatusBadRequest, "不允许删除的角色")
		return
	}
	err := roleModel.RoleDelete(id)
	if err == nil {
		c.OutDataJson("", iris.StatusOK, "success")
	} else {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
	}
}

//角色路由
func (c *UserController) GetRoleNodeBy(id uint) {
	Routers := []string{}
	for _, route := range c.Ctx.Application().GetRoutesReadOnly() {
		HandlerName := strings.Split(route.MainHandlerName(), ".")
		flag := false
		if strings.Index(HandlerName[2], "Public") != -1 {
			flag = true
		} else {
			for _, v := range middleware.PublicController {
				if HandlerName[1] == v {
					flag = true
				}
			}
		}

		if HandlerName[0] != "controller" {
			//flag = true
		}

		if flag == false {
			Routers = append(Routers, route.Name())
		}
	}
	//表单路由信息
	UserRoleRouteMode := model.NewUserRoleRoute()
	hasRoutes, _ := UserRoleRouteMode.GetAllRoutes(id) //已分配的权限
	UnRoutes := util.Difference(Routers, hasRoutes)    //未分配的权限
	c.OutDataJson(iris.Map{"hasRoutes": hasRoutes, "UnRoutes": UnRoutes, "AllRoutes": Routers}, iris.StatusOK, "success")
}

//角色路由分配
func (c *UserController) PostRoleNodeUpdate() {
	id := c.Ctx.PostValueIntDefault("id", 0)
	nodes := c.Ctx.PostValueDefault("nodes", "")
	if id == 0 {
		c.OutDataJson("", iris.StatusBadRequest, "参数错误")
		return
	}

	UserRoleRouteModel := model.NewUserRoleRoute()
	if err := UserRoleRouteModel.RealDel(id); err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}

	if nodes == "" {
		c.OutDataJson("", iris.StatusOK, "success")
		return
	}

	// BatchSave 批量插入数据
	var buffer bytes.Buffer
	sql := "insert into `user_role_route` (`role_id`,`path`) values"
	buffer.WriteString(sql)

	_nodes := strings.Split(nodes, ",")
	for i, v := range _nodes {
		if i == len(_nodes)-1 {
			buffer.WriteString(fmt.Sprintf("('%d','%s');", id, v))
		} else {
			buffer.WriteString(fmt.Sprintf("('%d','%s'),", id, v))
		}
	}
	if err := libs.DB.Exec(buffer.String()).Error; err != nil {
		c.OutDataJson("", iris.StatusBadRequest, err.Error())
		return
	}

	c.OutDataJson("", iris.StatusOK, "success")
}

/**
换取新的jwt token
*/
func (c *UserController) GetPublicNewToken() {
	user_model := model.NewUser()
	userInfo, err := user_model.GetUserByUserId(middleware.GetTokenUserId(c.Ctx))
	if err == nil {
		c.OutDataJson(middleware.GetUserToken(userInfo.UserId), iris.StatusOK, "success")
	} else {
		c.OutDataJson(err.Error(), iris.StatusBadRequest, "error")
	}
}
